package cn.yunhe.java.util;

import cn.yunhe.java.dto.MerchantDTO;
import cn.yunhe.java.service.MerchantService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.util.EncryptUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/***
 * 获取当前登录用户信息
 * 前端配置token，后续每次请求并通过Header方式发送至后端
 */
public class SecurityUtil {

    public static LoginUser getUser() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();

        HttpServletRequest request = servletRequestAttributes.getRequest();

        String token = request.getHeader("token");

        // token非空判断
        if(StringUtils.isEmpty(token)){
            throw new BusinessException(CommonErrorCode.E_200005);
        }
        LoginUser user = TokenUtil.parseToken(token, LoginUser.class);

        return user;
    }

    /**
     * 通过token获取所得用户
     * @return
     */
    public static Long getMerchantId(MerchantService merchantService) {

        // 通过TenantId获取MerchantDTO
        MerchantDTO merchant = merchantService.queryMerchantByTenantId(getUser().getTenantId());

        Long merchantId = merchant.getId();

        return merchantId;
    }

    /**
     * 转换明文jsonToken为用户对象
     * @param token
     * @return
     */
    public static LoginUser convertTokenToLoginUser(String token) {
        token = EncryptUtil.decodeUTF8StringBase64(token);
        LoginUser user = new LoginUser();
        JSONObject jsonObject = JSON.parseObject(token);
        String payload = jsonObject.getString("payload");
        Map<String, Object> payloadMap = JSON.parseObject(payload, Map.class);
        user.setPayload(payloadMap);
        user.setClientId(jsonObject.getString("client_id"));
        user.setMobile(jsonObject.getString("mobile"));
        user.setUsername(jsonObject.getString("user_name"));
        return user;
    }

}
